package com.yonyou.pmclouds.project.processor;

import com.yonyou.pmclouds.basecom.billstatus.BillStatusConst;
import com.yonyou.pmclouds.basecom.bp.processor.MultiProcessor;
import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.entity.SuperVO;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.util.BeanHelper;
import com.yonyou.pmclouds.basecom.util.CommonFieldConst;
import com.yonyou.pmclouds.picture.rmiitf.PictureRemoteService;
import com.yonyou.pmclouds.project.entity.ProjectBillVO;
import com.yonyou.pmclouds.project.mapper.ProjectBillMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class ProjectBillUpdateForUpdate<T extends SuperVO> implements SingleProcessor<T>, MultiProcessor<T> {
    private final ProjectBillMapper projectBillMapper;
    private final String billType;
    private PictureRemoteService pictureService;

    public ProjectBillUpdateForUpdate(ProjectBillMapper projectBillMapper, String billType, PictureRemoteService pictureService) {
        this.projectBillMapper = projectBillMapper;
        this.billType = billType;
        this.pictureService = pictureService;
    }

    @Override
    public void process(T[] vos, T[] origs) throws BusinessException {
        if (ArrayUtils.isEmpty(vos)) {
            return;
        }
        for (T vo : vos) {
            updateBillVO(vo);
        }

    }

    @Override
    public void process(T vo, T orig) throws BusinessException {
        updateBillVO(vo);
    }

    private void updateBillVO(T vo) {
        //创建项目单据对象
        ProjectBillVO billVO = new ProjectBillVO();
        //为其添加单据主键
        billVO.setPkBill((String) vo.pkFiledValue());
        //获取单据状态
        Byte status = (Byte) BeanHelper.getProperty(vo, CommonFieldConst.BILLSTATUS);
        //若单据状态为null，则默认为驳回再提交状态，即为6。因为只有在驳回后再提交时才会出现修改操作。
        if (status == null) {
            status = BillStatusConst.COMMON_COMMIT_STATUS;
        }
        //为对象状态属性赋值
        billVO.setBillStatus(status);
        //更新项目单据中单据状态
        projectBillMapper.updateFieldsWithoutFlag(billVO, new String[]{ProjectBillVO.BILL_STATUS});
        //更新图片状态，用于图片统计数量时，根据图片状态统计数量
        pictureService.updatePicBillStatusByBill((String) vo.pkFiledValue(), status);
    }

    @Component
    public static class ProjectBillForUpdateProcessorFactory<T extends SuperVO> {

        @Autowired
        private ProjectBillMapper projectBillMapper;
        @Autowired
        private PictureRemoteService pictureService;

        public ProjectBillUpdateForUpdate<T> getProcessor(String billType) {
            //new了一个自身对象，利用构造方法的方式为其自身的变量赋值
            return new ProjectBillUpdateForUpdate<>(projectBillMapper, billType, pictureService);
        }
    }
}
